define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'policy/index' + location.search,
                    add_url: 'policy/add',
                    edit_url: 'policy/edit',
                    del_url: 'policy/del',
                    multi_url: 'policy/multi',
                    import_url: 'policy/import',
                    table: 'policy',
                }
            });

            var table = $("#table");

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function () {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });

            $('.panel-heading a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var field =  $(this).closest("ul").data("field");
                var value = $(this).data("value");
                var options = table.bootstrapTable('getOptions');
                options.pageNumber = 1;
                var queryParams = options.queryParams;
                options.queryParams = function (params) {
                    params = queryParams(params);
                    var filter = params.filter ? JSON.parse(params.filter) : {};
                    if (value !== '' && value != 'all') {
                        filter[field] = value;
                    } else {
                        delete filter[field];
                    }
                    params.filter = JSON.stringify(filter);
                    params.op = JSON.stringify([field,"="]);
                    return params;
                };
                return false;
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title')},
                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: {"1": __('Status 1'), "2": __('Status 2')},
                            formatter: Table.api.formatter.status
                        },
                        {
                            field: 'create_time',
                            title: __('Create_time'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            $(".btn-product").click(function () {
                var ids = JSON.stringify(Table.api.selectedids(table));
                Fast.api.open('policy/product?ids=' + ids, "新增", {area: ["100%", "100%"],closeBtn :0,});
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            var product_id = Config.product_id;
            var cardArr = [];
            var tranArr = [];
            var rateArr = [];
            var channelArr = [];

            $(document).ready(function () {
                $("#c-card_type").find("option:selected").each(function () {
                    cardArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
                $("#c-transaction_type_ids").find("option:selected").each(function () {
                    tranArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
                $("#c-rate_ids").find("option:selected").each(function () {
                    rateArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
                $("#c-channel_ids").find("option:selected").each(function () {
                    channelArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
            });

            $(document).on('change', "#c-card_type", function () {
                cardArr = [];
                $(this).find("option:selected").each(function () {
                    cardArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
            });
            $(document).on('change', "#c-transaction_type_ids", function () {
                tranArr = [];
                $(this).find("option:selected").each(function () {
                    tranArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
            });
            $(document).on('change', "#c-rate_ids", function () {
                rateArr = [];
                $(this).find("option:selected").each(function () {
                    rateArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
            });
            $(document).on('change', "#c-channel_ids", function () {
                channelArr = [];
                $(this).find("option:selected").each(function () {
                    channelArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
            });

            //批量设置分润
            $("#patch").click(function () {
                let arr = [];
                $("input[type=checkbox]:checked").each(function () {
                    arr.push($(this).val());
                });
                if (arr.length == 0) {
                    Toastr.error("请选择数据！");
                    return false;
                }
                Layer.prompt({title: __('请输入数值'), formType: 0}, function (value, index) {
                    $.each(arr, function (index, item) {
                        $("#" + item).val(value);
                    })
                    Layer.close(index);
                });
            });

            //达标多加
            $("#more").click(function () {
                let html = '<tr>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="day_start[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="day_limit[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="money[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="standard_agent[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="standard_agency[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="standard_core[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <button type="button" class="btn btn-warning btn-embossed deletes">删除</button>\n' +
                    '          </td>\n' +
                    '      </tr>';
                $(".standard-table").append(html);
            });

            //达标删除
            $(document).on('click', ".deletes", function () {
                $(this).parent().parent().remove();
            })

            $(document).on('click', "#start_setting", function () {
                profit();
            })

            function profit(){
                var index = layer.load();

                if(cardArr.length === 0 || tranArr.length === 0 || rateArr.length === 0 || channelArr.length === 0){
                    layer.msg("设置未选择！！！");
                    layer.close(index);
                    return false;
                }

                $(".profit_setting").remove();
                let html = '';
                $.each(cardArr,function (card_index,card_item) {
                    $.each(tranArr,function (tran_index,tran_item) {
                        $.each(rateArr,function (rate_index,rate_item) {
                            $.each(channelArr,function (channel_index,channel_item) {
                                if(Config.is_admin){
                                    html += "<tr class='profit_setting'>\n" +
                                        "    <td>\n" +
                                        "        <input type=\"checkbox\" value=\""+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\">\n" +
                                        "    </td>\n" +
                                        "    <td>"+card_item.title+"</td>\n" +
                                        "    <td>"+tran_item.title+"</td>\n" +
                                        "    <td>"+rate_item.title+"</td>\n" +
                                        "    <td>"+channel_item.title+"</td>\n" +
                                        "    <td class='form-group'>\n" +
                                        "        <div class=\"col-xs-12 col-sm-8\">\n" +
                                        "            <input type=\"hidden\" name=\"card[]\" value=\""+card_item.id+"\">\n" +
                                        "            <input type=\"hidden\" name=\"tran[]\" value=\""+tran_item.id+"\">\n" +
                                        "            <input type=\"hidden\" name=\"rate[]\" value=\""+rate_item.id+"\">\n" +
                                        "            <input type=\"hidden\" name=\"channel[]\" value=\""+channel_item.id+"\">\n" +
                                        "            <input id=\""+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\" data-rule=\"required\" class=\"form-control\" name=\"profit[]\" type=\"text\" value=\"\">\n" +
                                        "        </div>\n" +
                                        "    </td>\n" +
                                        "    <td class='form-group'>\n" +
                                        "        <div class=\"col-xs-12 col-sm-8\">\n" +
                                        "            <input id=\"base"+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\" data-rule=\"required\" class=\"form-control\" name=\"profit_base[]\" type=\"text\" value=\"\">\n" +
                                        "        </div>\n" +
                                        "    </td>\n" +
                                        "    <td class='form-group'>\n" +
                                        "        <div class=\"col-xs-12 col-sm-8\">\n" +
                                        "            <input id=\"hide"+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\" data-rule=\"required\" class=\"form-control\" name=\"profit_hide[]\" type=\"text\" value=\"\">\n" +
                                        "        </div>\n" +
                                        "    </td>\n" +
                                        "</tr>";
                                }else{
                                    let policy_id = Config.policy_id;
                                    Fast.api.ajax({
                                        url: "policy/profit",
                                        async: false,
                                        data: {policy_id: policy_id,card_id: card_item.id,tran_id: tran_item.id,rate_id: rate_item.id,channel_id: channel_item.id},
                                    }, function (data, ret) {
                                        let base_range = data.base > 0 ? "range(0~"+data.base+")" : "";
                                        let hide_range = data.hide > 0 ? "range(0~"+data.hide+")" : "";
                                        html += "<tr class='profit_setting'>\n" +
                                            "    <td>\n" +
                                            "        <input type=\"checkbox\" value=\""+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\">\n" +
                                            "    </td>\n" +
                                            "    <td>"+card_item.title+"</td>\n" +
                                            "    <td>"+tran_item.title+"</td>\n" +
                                            "    <td>"+rate_item.title+"</td>\n" +
                                            "    <td>"+channel_item.title+"</td>\n" +
                                            "    <td class='form-group'>\n" +
                                            "        <div class=\"col-xs-12 col-sm-8\">\n" +
                                            "            <input type=\"hidden\" name=\"card[]\" value=\""+card_item.id+"\">\n" +
                                            "            <input type=\"hidden\" name=\"tran[]\" value=\""+tran_item.id+"\">\n" +
                                            "            <input type=\"hidden\" name=\"rate[]\" value=\""+rate_item.id+"\">\n" +
                                            "            <input type=\"hidden\" name=\"channel[]\" value=\""+channel_item.id+"\">\n" +
                                            "            <input id=\"base"+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\" data-rule=\"required;"+base_range+"\" class=\"form-control\" name=\"profit_base[]\" type=\"text\" value=\"\">\n" +
                                            "        </div>\n" +
                                            "    </td>\n" +
                                            "    <td class='form-group'>\n" +
                                            "        <div class=\"col-xs-12 col-sm-8\">\n" +
                                            "            <input id=\"hide"+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\" data-rule=\"required;"+hide_range+"\" class=\"form-control\" name=\"profit_hide[]\" type=\"text\" value=\"\">\n" +
                                            "        </div>\n" +
                                            "    </td>\n" +
                                            "</tr>";
                                        return false;
                                    });
                                }
                            });
                        });
                    });
                });

                $(".profit-table").append(html);

                layer.close(index);
            }

            Controller.api.bindevent();
        },
        product: function () {
            $(".product").click(function () {
                let id = $(this).data("id");
                parent.Layer.close();
                if(Config.is_admin){
                    Fast.api.open('policy/setting?ids=' + id, "设置", {area: ["100%", "100%"]});
                }else{
                    let policy_id = $(this).data("policy");
                    Fast.api.open('policy/setting?ids=' + id + '&policy_id=' + policy_id, "设置", {area: ["100%", "100%"]});
                }
            });

            $(document).on('click', "#close-open", function () {
                parent.$("#table").bootstrapTable('refresh');
                var index = parent.Layer.getFrameIndex(window.name);
                parent.Layer.close(index);
                return false;
            })
            Controller.api.bindevent();
        },
        list: function () {
            $(".policy").click(function () {
                let policy_id = $(this).data("id");
                let id = Config.product_id;
                Fast.api.open('policy/setting?ids=' + id + '&policy_id=' +policy_id, "设置", {area: ["100%", "100%"]});
            });
            Controller.api.bindevent();
        },
        setting: function () {
            var product_id = Config.product_id;
            var cardArr = [];
            var tranArr = [];
            var rateArr = [];
            var channelArr = [];

            $(document).on('change', "#c-card_type", function () {
                cardArr = [];
                $(this).find("option:selected").each(function () {
                    cardArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
            })
            $(document).on('change', "#c-transaction_type_ids", function () {
                tranArr = [];
                $(this).find("option:selected").each(function () {
                    tranArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
            })
            $(document).on('change', "#c-rate_ids", function () {
                rateArr = [];
                $(this).find("option:selected").each(function () {
                    rateArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
            })
            $(document).on('change', "#c-channel_ids", function () {
                channelArr = [];
                $(this).find("option:selected").each(function () {
                    channelArr.push({
                        "id":$(this).val(),
                        "title":$(this).text()
                    });
                });
            })

            //批量设置分润
            $("#patch").click(function () {
                let arr = [];
                $("input[type=checkbox]:checked").each(function () {
                    arr.push($(this).val());
                });
                if (arr.length == 0) {
                    Toastr.error("请选择数据！");
                    return false;
                }
                Layer.prompt({title: __('请输入数值'), formType: 0}, function (value, index) {
                    $.each(arr, function (index, item) {
                        $("#" + item).val(value);
                    })
                    Layer.close(index);
                });
            });

            //达标多加
            $("#more").click(function () {
                let html = '<tr>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="day_start[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="day_limit[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="money[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="standard_agent[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="standard_agency[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <input type="text" class="form-control" name="standard_core[]" value="">\n' +
                    '          </td>\n' +
                    '          <td>\n' +
                    '              <button type="button" class="btn btn-warning btn-embossed deletes">删除</button>\n' +
                    '          </td>\n' +
                    '      </tr>';
                $(".standard-table").append(html);
            });

            //达标删除
            $(document).on('click', ".deletes", function () {
                $(this).parent().parent().remove();
            })

            $(document).on('click', "#start_setting", function () {
                profit();
            })

            function profit(){
                var index = layer.load();

                if(cardArr.length === 0 || tranArr.length === 0 || rateArr.length === 0 || channelArr.length === 0){
                    layer.msg("设置未选择！！！");
                    layer.close(index);
                    return false;
                }

                $(".profit_setting").remove();
                let html = '';
                $.each(cardArr,function (card_index,card_item) {
                    $.each(tranArr,function (tran_index,tran_item) {
                        $.each(rateArr,function (rate_index,rate_item) {
                            $.each(channelArr,function (channel_index,channel_item) {
                                if(Config.is_admin){
                                    html += "<tr class='profit_setting'>\n" +
                                        "    <td>\n" +
                                        "        <input type=\"checkbox\" value=\""+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\">\n" +
                                        "    </td>\n" +
                                        "    <td>"+card_item.title+"</td>\n" +
                                        "    <td>"+tran_item.title+"</td>\n" +
                                        "    <td>"+rate_item.title+"</td>\n" +
                                        "    <td>"+channel_item.title+"</td>\n" +
                                        "    <td class='form-group'>\n" +
                                        "        <div class=\"col-xs-12 col-sm-8\">\n" +
                                        "            <input type=\"hidden\" name=\"card[]\" value=\""+card_item.id+"\">\n" +
                                        "            <input type=\"hidden\" name=\"tran[]\" value=\""+tran_item.id+"\">\n" +
                                        "            <input type=\"hidden\" name=\"rate[]\" value=\""+rate_item.id+"\">\n" +
                                        "            <input type=\"hidden\" name=\"channel[]\" value=\""+channel_item.id+"\">\n" +
                                        "            <input id=\""+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\" data-rule=\"required\" class=\"form-control\" name=\"profit[]\" type=\"text\" value=\"\">\n" +
                                        "        </div>\n" +
                                        "    </td>\n" +
                                        "    <td class='form-group'>\n" +
                                        "        <div class=\"col-xs-12 col-sm-8\">\n" +
                                        "            <input id=\"base"+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\" data-rule=\"required\" class=\"form-control\" name=\"profit_base[]\" type=\"text\" value=\"\">\n" +
                                        "        </div>\n" +
                                        "    </td>\n" +
                                        "    <td class='form-group'>\n" +
                                        "        <div class=\"col-xs-12 col-sm-8\">\n" +
                                        "            <input id=\"hide"+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\" data-rule=\"required\" class=\"form-control\" name=\"profit_hide[]\" type=\"text\" value=\"\">\n" +
                                        "        </div>\n" +
                                        "    </td>\n" +
                                        "</tr>";
                                }else{
                                    let policy_id = Config.policy_id;
                                    Fast.api.ajax({
                                        url: "policy/profit",
                                        async: false,
                                        data: {policy_id: policy_id,card_id: card_item.id,tran_id: tran_item.id,rate_id: rate_item.id,channel_id: channel_item.id},
                                    }, function (data, ret) {
                                        let base_range = data.base > 0 ? "range(0~"+data.base+")" : "";
                                        let hide_range = data.hide > 0 ? "range(0~"+data.hide+")" : "";
                                        let base_read = data.base == 0 ? "readonly" : "";
                                        let hide_read = data.hide == 0 ? "readonly" : "";
                                        let base_value = data.base == 0 ? "value = '0'" : "";
                                        let hide_value = data.hide == 0 ? "value = '0'" : "";
                                        html += "<tr class='profit_setting'>\n" +
                                                "    <td>\n" +
                                                "        <input type=\"checkbox\" value=\""+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\">\n" +
                                                "    </td>\n" +
                                                "    <td>"+card_item.title+"</td>\n" +
                                                "    <td>"+tran_item.title+"</td>\n" +
                                                "    <td>"+rate_item.title+"</td>\n" +
                                                "    <td>"+channel_item.title+"</td>\n" +
                                                "    <td class='form-group'>\n" +
                                                "        <div class=\"col-xs-12 col-sm-8\">\n" +
                                                "            <input type=\"hidden\" name=\"card[]\" value=\""+card_item.id+"\">\n" +
                                                "            <input type=\"hidden\" name=\"tran[]\" value=\""+tran_item.id+"\">\n" +
                                                "            <input type=\"hidden\" name=\"rate[]\" value=\""+rate_item.id+"\">\n" +
                                                "            <input type=\"hidden\" name=\"channel[]\" value=\""+channel_item.id+"\">\n" +
                                                "            <input id=\"base"+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\" placeholder=\"0~"+data.base+"\" data-rule=\"required;"+base_range+"\" class=\"form-control\" "+base_read+" name=\"profit_base[]\" type=\"text\" "+base_value+">\n" +
                                                "        </div>\n" +
                                                "    </td>\n" +
                                                "    <td class='form-group'>\n" +
                                                "        <div class=\"col-xs-12 col-sm-8\">\n" +
                                                "            <input id=\"hide"+card_item.id+tran_item.id+rate_item.id+channel_item.id+"\" placeholder=\"0~"+data.hide+"\" data-rule=\"required;"+hide_range+"\" class=\"form-control\""+hide_read+" name=\"profit_hide[]\" type=\"text\" "+hide_value+">\n" +
                                                "        </div>\n" +
                                                "    </td>\n" +
                                                "</tr>";
                                        return false;
                                    });
                                }
                            });
                        });
                    });
                });

                $(".profit-table").append(html);

                layer.close(index);
            }

            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
